<?php

namespace App\Http\Controllers\Admin;

use App\CodeResponse;
use App\Models\Permissions;
use App\Models\Role;
use App\Models\Users;
use App\Models\UserLoginLog;
use App\Services\SchoolService;
use App\Services\UsersServices;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Session\Session;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;

class AuthController extends AdminController
{
    //
    public function adminLogin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }

        $user =  UsersServices::getInstance()->getByUsresname($request->username);
        if(is_null($user)){
            return $this->fail(CodeResponse::AUTH_INVALID_ACCOUNT);
        }
//        $isPass = Hash::check($request->password, $user->getAuthPassword());
//        if (!$isPass) {
//            return $this->fail(CodeResponse::AUTH_INVALID_ACCOUNT, '账号密码不对');
//        }
        $bool = auth()->attempt($request->all());

        if (!$bool) {
            return $this->fail(CodeResponse::AUTH_INVALID_ACCOUNT, '账号密码不对');
        }
        //获取用户权限
        $userModel = auth()->user();

        if($userModel->type != 0 && !empty($userModel->role_id)){
            $roleModel = Role::find($userModel->role_id);
            if(!$roleModel){
                return $this->fail(CodeResponse::AUTH_INVALID_ROLE);
            }
            $nodeArr =$roleModel->permissions()->pluck('permissions.name','permissions.id')->toArray();
            session(['admin.auth' => $nodeArr]);

        }else{
            session(['admin.auth' => []]);
        }

        //获取token
        $token = Auth::guard('admin')->login($user);

        //更新登录的信息
        $user->last_login_time = now()->toDateTimeString();
        $user->last_login_ip = $request->getClientIp();
        $user->last_session = Session()->getId();

        if (!$user->save()) {
            return $this->fail(CodeResponse::UPDATED_FAIL);
        }
        $schoolName = '';
        $schoolAddress = '';
        if(isset($user->school_id)){
            $school =  SchoolService::getInstance()->getSchoolInfo($user->school_id);
            if(isset($school)){
                $schoolName =$school->name;
                $schoolAddress =$school->address;
            }
        }
        //获取IP地址所在地区
        $ip = $request->getClientIp();
        $addressInfo = $this->info($ip);

        $address = '';
        if($addressInfo != 'unknown'){
            $address .= $addressInfo['country'].' ';
            $address .= $addressInfo['region'].' ';
            $address .= $addressInfo['city'].' ';
//            $address .= $addressInfo['isp'];
        }
        //添加登录日志
        $userLoginLog = new UserLoginLog();
        $userLoginLog->users_id = $user->id;
        $userLoginLog->username = $user->username;
        $userLoginLog->name = $user->name;
        $userLoginLog->sex = $user->sex;
        $userLoginLog->type = $user->type;
        $userLoginLog->school_id = $user->school_id;
        $userLoginLog->last_login_time = $user->last_login_time;
        $userLoginLog->last_login_address = $address;
        $userLoginLog->last_login_ip = $ip;
        $userLoginLog->last_session = Session()->getId();
        $userLoginLog->save();

        //组装数据并返回
        return $this->success([
            'token' => $token,
            'userInfo' => [
                'users_id' => $user->id,
                'type' => $user->type,
                'school_id' => $user->school_id,
                'school_name' => $schoolName,
                'school_address' => $schoolAddress,
                'name' => $user->username,
                'avatarUrl' => $user->pic,
                'loginTime' => $user->last_login_time,
                'userLoginLogId' => $userLoginLog->id,

            ]
        ]);

    }

    public function logout(Request $request){

        $validator = Validator::make($request->all(), [
            'userLoginLogId' => 'required|integer',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }

         UserLoginLog::query()
                ->where('id', $request->userLoginLogId)
                ->update([
                    'last_Log_out_time' => now()->toDateTimeString(),
                ]);


        auth()->logout();
        return $this->success();
    }
    public function menuList(){
//        dd(session('admin.auth'));
        $auth = session('admin.auth');

        // 读取菜单
        $menuData = (new Permissions())->treeData(array_keys($auth));
        return $this->success($menuData);
    }

    public function info($ip) {
        // $response = Http::get("http://ip.taobao.com/outGetIpInfo?ip=$ip&accessKey=alibaba-inc");
        $response = Http::get('http://ip.taobao.com/outGetIpInfo', [
            'ip' => $ip,
            'accessKey' => 'alibaba-inc',
        ]);
        $data =$response->json();

        if (isset($data) && $data['code']==0) {
            return $data['data'];
        } else {
            return 'unknown';
        }
    }
    public static function getTrustedProxiesIp(){
        \request()->setTrustedProxies(\request()->getClientIps(),Request::HEADER_X_FORWARDED_FOR);
        return \request()->getClientIp();
    }

}
